<template>
  <el-select
      v-model="unitNo.unitNo"
      placeholder="请选择你想要管理的部门..."
      style="width: 50%"
      @change="changeUnitHumanForm()"
  >
    <el-option
        v-for="x in allUnit"
        :key="x.unitNo"
        :label="x.unitName"
        :value="x.unitNo"
    />
  </el-select>
  <el-button
      style="margin-left: 10px"
      size="small"
      type="primary"
      icon="plus"
      @click="this.addPersonDialog=true"
  >新增
  </el-button>
  <el-link href="http://172.16.76.87:8888/down/sXoZNFUL9CjV">
    <el-button
        style="margin-left: 10px"
        size="small"
        type="primary"
        icon="plus">
      下载模板
    </el-button>
  </el-link>
  <el-button
      style="margin-left: 10px"
      size="small"
      type="primary"
      icon="plus"
      @click="this.importTwo=true"
  >批量导入
  </el-button>
      <el-button
          icon="Edit"
          size="small"
          type="primary"
          :disabled="this.selectedRows.length===0"
          @click="this.PermissionsDialog=true"
      >授权
      </el-button>
  <el-table
      height="80vh"
      ref="selectedRows"
      row-key="id"
      :data="UnitHuman"
      v-model="selectedRows"
      @selection-change="handleSelectionChange"
      border style="width: 100%"
      :header-cell-style="{'text-align':'center'}"
      :cell-style="{'text-align':'center'}">
    <el-table-column
        type="selection"
        width="55">
    </el-table-column>
    <el-table-column prop="name" label="姓名" width="150"/>
    <el-table-column prop="accountNo" label="学号" width="150"/>
    <el-table-column prop="classNo" label="班级" width="150"/>
    <el-table-column prop="unitName" label="部门" width="150"/>
    <el-table-column prop="unitPosition" label="职位" width="180"/>
    <el-table-column prop="unitDuty" label="职责" width="300"/>
    <el-table-column prop="startTime" label="开始担任时间" width="220"/>
    <el-table-column prop="endTime" label="担任结束时间" width="220"/>
    <el-table-column align="center" fixed="right" prop="operate" label="操作" width="150">
      <template v-slot="scope">
        <el-button
            size="small"
            type="warning" icon="Refresh"
            @click="this.$router.push({path:'/myUnit',query: {accountNo:scope.row.accountNo,unitNo:scope.row.unitNo}})"
        >修改
        </el-button>
        <br>
        <el-button
            icon="Delete"
            size="small" type="danger"
            @click="deleteData(scope.row)"
        >删除
        </el-button>
      </template>
    </el-table-column>
  </el-table>
  <el-pagination
      class="pagination"
      :page-size="pageSize"
      small
      :pager-count="5"
      :page-sizes="[50, 100 , 200 , 500,1000,2000,5000]"
      :total="total"
      layout="total, sizes, prev, pager, next"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange">
  </el-pagination>
  <!--  新增部门成员弹窗-->
  <el-dialog
      v-model="addPersonDialog"
      :close-on-click-modal="false"
      title="新增部门成员"
      width="550px">
    <el-form :model="addPersonInform" ref="addPersonInform">
      <el-form-item label="部门" prop="unitNo"
                    :rules="[{ required: true, message: '请选择部门名称', trigger: 'blur' }]">
        <!--      选择部门-->
        <el-select v-model="addPersonInform.unitNo" placeholder="请选择部门">
          <el-option
              v-for="key in allUnit"
              :key="key.id"
              :label="key.unitName"
              :value="key.unitNo">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="学号" prop="accountNo" :rules="[{ required: true, message: '请输入学号', trigger: 'blur' }]">
        <el-input v-model="addPersonInform.accountNo" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="担任职位" prop="unitPosition"
                    :rules="[{ required: true, message: '请输入担任职位', trigger: 'blur' }]">
        <el-input v-model="addPersonInform.unitPosition" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="担任职责" prop="unitDuty"
                    :rules="[{ required: true, message: '请输入担任职责', trigger: 'blur' }]">
        <el-input v-model="addPersonInform.unitDuty" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="担任开始时间" prop="startTime"
                    :rules="[{ required: true, message: '请选择担任开始时间', trigger: 'blur' }]">
        <el-date-picker
            v-model="this.addPersonInform.startTime"
            style="width: 100%"
            value-format="YYYY-MM-DD"
            type="date"
            placeholder="请选择担任开始时间"
            clearable
        />
      </el-form-item>
      <el-form-item label="担任结束时间" prop="endTime"
                    :rules="[{ required: true, message: '请选择担任结束时间', trigger: 'blur' }]">
        <el-date-picker
            v-model="this.addPersonInform.endTime"
            style="width: 100%"
            value-format="YYYY-MM-DD"
            type="date"
            placeholder="请选择担任开始时间"
            clearable
        />
      </el-form-item>
      <el-form-item label="备注" prop="remark" :rules="[{ required: true, message: '请输入备注', trigger: 'blur' }]">
        <el-input v-model="addPersonInform.remark" autocomplete="off"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <!--      <el-button @click="dialogVisible = false">取 消</el-button>-->
      <el-button type="primary" @click="confirmChange()">确 定</el-button>
    </div>
  </el-dialog>
  <el-dialog
      v-model="PermissionsDialog"
      :close-on-click-modal="false"
      title="授予权限"
      :before-close="permissionsDialogClose"
      width="550px">
    <el-checkbox-group
        v-model="addPermissions"
        :min="1">
      <el-checkbox v-for="permission in permissions" :label="permission.label" :value="permission.value"
                   :key="permission.value">{{ permission.label }}
      </el-checkbox>
    </el-checkbox-group>
    <div slot="footer" class="dialog-footer">
      <!--      <el-button @click="dialogVisible = false">取 消</el-button>-->
      <el-button type="primary" @click="confirmAddPermissions()">确 定</el-button>
    </div>
  </el-dialog>
  <el-dialog
      v-model="importTwo"
      :close-on-click-modal="false"
      title="批量上传部门成员信息"
      width="550px">
    <el-upload
        accept=".xls,.xlsx"
        :before-upload="checkFileType"
        :headers="this.headerObject"
        id="uploadShowOrHide"
        class="upload-demo"
        drag
        :action="serverIp() + '/api/related_unit/importToMySQL'"
        limit="1"
        :on-success="finish"
    >
      <el-icon class="el-icon--upload">
        <upload-filled/>
      </el-icon>
      <div class="el-upload__text">
        将文件移在这 或 <em>点击上传</em>
      </div>
      <template #tip>
        <div class="el-upload__tip">
          xls、xlsx 文件应小于 10MB
        </div>
      </template>
    </el-upload>
    <div slot="footer" class="dialog-footer">
      <!--      <el-button @click="dialogVisible = false">取 消</el-button>-->
      <el-button type="primary" @click="confirmAddPerson()">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import request from "@/util/request.js";
import {READ_UNIT_HUMAN} from "@/util/config.js";
import {ElMessage, ElMessageBox} from "element-plus";
import {serverIp} from "../../../public/static/config.js";
import aes from "@/util/aes.js";
import clipboard from 'clipboard';
export default {
  data() {
    return {
      permissions: [
        {
          label: "部门成员管理",
          value: "05",
        },
        {
          label: "照片管理",
          value: "10"
        },
        {
          label: "活动管理",
          value: "08"
        },
        {
          label: "新闻管理",
          value: "04"
        },
        {
          label: "通知管理",
          value: "06"
        },
        {
          label: "大事管理",
          value: "09"
        },
        {
          label: "意见反馈查看员",
          value: "07"
        },
        {
          label: "照片管理员",
          value: "10"
        },
        {
          label: "综测管理员",
          value: "11"
        },
      ],
      headerObject: {
        "account": JSON.parse(localStorage.getItem('user')).accountNo,
        "token": JSON.parse(localStorage.getItem('user')).token
      },
      selectedRows: [], // 选中人
      addPermissions: [], // 选中的权限
      PermissionsDialog: false,// 授权弹窗
      addPersonDialog: false, // 新增信息弹窗
      importTwo: false,  // 批量导入弹窗
      addPersonInform: {},
      unitNo:{},
      UnitHuman:[],
      allUnit:[],
      pageNum: 1, // 页码
      pageSize: 50,  // 页长
      total: 0,  // 总表长
      roleNo: [] // 角色编号
    }
  },
  created() {
    this.setRoleNo()
  },
  methods: {
    permissionsDialogClose() {
      this.addPermissions = []
      this.PermissionsDialog = false
    },
    confirmAddPerson() {
      window.location.reload()
    },
    serverIp() {
      return serverIp
    },
    // 检查文件类型
    checkFileType(file) {
      const fileName = file.name
      const fileType = fileName.substring(fileName.lastIndexOf('.'))
      // jpeg,.png,.jpg,.bmp,.gif
      if (
          fileType === '.xls' ||
          fileType === '.xlsx'
      ) {
        // 不处理
      } else {
        this.$message.error(
            '不是.xls,.xlsx文件,请上传正确的Excel类型'
        )
        return false
      }
    },
    finish(res) {
      res = aes.decrypt(res)
      if (res.code !== '200') {
        ElMessageBox.alert(res.data, {
          title: '存在空单元格，导致以下学号导入失败',
          confirmButtonText: '确定',
        }).then(() => {
          navigator.clipboard.write(res.data).then(() => {
            ElMessage({
              type: 'success',
              message: '已复制剪切版!'
            });
          })
        });
      }
      this.$message.success('上传成功');
    },
    // 选行
    handleSelectionChange(val) {
      this.selectedRows = val;
      console.log(this.selectedRows)
    },
    // 授予权限
    async confirmAddPermissions() {
      if (this.addPermissions.length === 0) {
        ElMessage({
          type: 'error',
          message: '权限不能为空!'
        });
        return false
      }
      let permission=""//权限用,隔开
      this.addPermissions.forEach((item,index)=>{
        if (index===0){
          permission+=item
        }else {
          permission+=","+item
        }
      })
      let add = []
      this.selectedRows.forEach((item,index)=>{
        let account= {accountNo:"",roleNo:""}
        account.accountNo=item.accountNo
        account.roleNo=permission
        add.push(account)
      })
    await this.authorization(add)
    },
    async authorization(add){
      request.post("/info_account/authorization",add).then(res=>{
        ElMessage({
          type: 'success',
          message: '授权成功!'
        });
        location.reload()
      })
    },
    // 部门新增用户
    confirmChange() {
      request.post("/related_unit/edit", this.addPersonInform).then(res => {
        if (res.data.data) {
          ElMessage({
            type: 'success',
            message: '新增成功!'
          });
          location.reload()
        } else {
          ElMessage({
            type: 'error',
            message: '已存在!'
          });
        }
      })
    },
    // 删除
    deleteData(scope) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 确认删除，向服务器发送请求
        request.get("/related_unit/deleteById?id=" + scope.id).then(res => {
          // 删除成功，重新获取数据
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          location.reload()
        })
      })
    },
    // 用户角色赋值
    setRoleNo() {
      let roleNo = JSON.parse(localStorage.getItem("user")).roleNo
      if (roleNo.includes(",")) {
        this.roleNo = roleNo.split(',')
      } else {
        this.roleNo.push(roleNo)
      }
      for (let item of this.roleNo) {
        if (READ_UNIT_HUMAN.includes(item)) {
          this.getAllUnit()
          return
        }
      }
      this.getMyUnit()
    },
    // 教师、管理员获取所有
    getAllUnit(){
      request.get("/info_unit/getAllSed").then(res => {
        if (res.data.code === '200') {
          this.allUnit = res.data.data
          this.unitNo.unitNo = this.allUnit.at(0).unitNo
          this.changeUnitHumanForm()
        }
      })
    },
    // 获取当前角色的
    getMyUnit() {
      request.get("/related_unit/getByAccountNo?accountNo="+JSON.parse(localStorage.getItem('user')).accountNo).then(res=>{
        if (res.data.code === '200'){
          this.allUnit = res.data.data
          this.unitNo.unitNo = this.allUnit.at(0).unitNo
          this.changeUnitHumanForm()
        }
      })
    },
    changeUnitHumanForm(){
      this.UnitHuman.unitNo = this.unitNo.unitNo
      request.get("/related_unit/getPersonByNo?unitNo="+this.UnitHuman.unitNo + "&pageNum=" + this.pageNum + "&pageSize=" + this.pageSize).then(res =>{
        if (res.data.code === '200') {
          console.log(res.data)
          for (let key in res.data.data) {
            if (key === "records") {
              this.UnitHuman = res.data.data[key];
            } else if (key === "total") {
              this.total = res.data.data[key];
            }
          }
        }
      })
    },
    //表尾分页
    handleSizeChange(val) {
      this.pageSize = val;
      this.changeUnitHumanForm();
    },
    handleCurrentChange(val) {
      this.pageNum = val;
      this.changeUnitHumanForm();
    },
  }
}
</script>

<style scoped>
</style>
